package com.zt.student.common;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.zt.common.common.ApiException;
import com.zt.common.common.CodeMsg;
import com.zt.common.pojo.common.JsonResult;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * description:
 * author:张腾
 * date:2021-05-21
 */

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Log log = LogFactory.get();

    /*自定义异常*/
    @ExceptionHandler(value = ApiException.class)
    public JsonResult apiExceptionHandler(ApiException e){
        log.error("发生业务异常：" + e.getMessage(),e);
        return JsonResult.error(e.getCodeMsg());
    }

    /*空指针异常*/
    @ExceptionHandler(value = NullPointerException.class)
    public JsonResult nullPointExceptionHandler(NullPointerException e){
        log.error("发生空指针异常：" + e.getMessage(),e);
        return JsonResult.error(CodeMsg.BODY_NOT_MATCH);
    }

    /*运行时异常*/
    @ExceptionHandler(value = RuntimeException.class)
    public JsonResult notFountExceptionHandler(RuntimeException e){
        log.error("发生运行时异常：" + e.getMessage(),e);
        return JsonResult.error(CodeMsg.NOT_FOUNT);
    }

    /*请求方法不支持异常*/
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public JsonResult methodExceptionHandler(HttpRequestMethodNotSupportedException e){
        log.error("请求方法不支持异常：" + e.getMessage(),e);
        return JsonResult.error(CodeMsg.METHOD_NOT_MATCH);
    }

    /*参数缺失校验异常*/
    @ExceptionHandler({MissingServletRequestParameterException.class})
    public JsonResult handleMissingParamsException(MissingServletRequestParameterException e){
        log.error("发生参数校验异常：" + e.getMessage(),e);
        return JsonResult.error(CodeMsg.BIND_ERROR,"缺少参数：" + e.getParameterName());
    }

    /* 身份校验异常 */
    @ExceptionHandler(value = AuthenticationException.class)
    public JsonResult handleAuthenticationException(AuthenticationException e){
        log.error("身份验证异常：" + e.getMessage(),e);
        return JsonResult.error(CodeMsg.VERIFY_ERROR,e.getMessage());
    }

    /*其他异常*/
    @ExceptionHandler(value = Exception.class)
    public JsonResult exceptionHandler(Exception e){
        log.error("发生未知异常：" + e.getMessage(),e);
        return JsonResult.error(CodeMsg.INTERNAL_SERVER_ERROR);
    }

}
